import copy

# TODO


def redis_key_name_encode(key_name):
    key_name.replace('-', '\\-')


def safe_encode(s):
    if type(s) == unicode:
        return s.encode('utf-8')
    else:
        return str(s)


def anagram(arr):
    if not arr:
        return [[]]
    return [[arr[a]] + j for a in range(len(arr)) for j in anagram(arr[:a]+arr[a+1:])]


def exhaustive(arr):
    if not arr:
        yield []
    else:
        for n in range(arr[0][1]+1):
            _arr = exhaustive(arr[1:])
            _0 = (arr[0][0], n) + arr[0][2:]
            for i in _arr:
                yield [_0]+i


def arr_sum(arr):
    return sum(i[0] * i[1] for i in arr)


def arr_push(arr_r, arr_l):
    dr = dict(arr_r)
    dl = dict(arr_l)
    keys = set(dr.keys()+dl.keys())
    return sorted([(k, dr.get(k, 0) + dl.get(k, 0)) for k in keys], key=lambda x: x[0], reverse=True)


def arr_sub(arr_r, arr_l):
    reversed_arr_l = [(i[0], -i[1]) for i in arr_l]
    return arr_push(arr_r, reversed_arr_l)


def close_to(num):
    def _close_to(arr):
        near = arr
        _sum = arr_sum(arr)
        for a in exhaustive(arr):
            __s = arr_sum(a)
            if __s == num:

                print 'num:%s,near:%s' % (num, a)
                return a
            elif __s > num:
                if __s < _sum:
                    _sum = __s
                    near = a
        print 'near:', near
        return near
    return _close_to


def get_shop_urls_namespace(time):
    return 'eleme-urls-' + time

def get_menu_namespace(time, shop_url):
    return __redis_namespace('eleme-m', time, shop_url)

def get_split_menu_namespace(time, shop_url):
    return __redis_namespace('eleme-s', time, shop_url)

def get_discount_key(time, shop_url):
    return __redis_namespace('eleme-discount', time, shop_url)

def __redis_namespace(prefix, time, shop_url):
    return '-'.join([prefix, time, shop_url])
